package com.hllxd.hism.star.util;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * Created by Administrator on 2017/12/25.
 */
public class Utils {

//    public static String getReverseInteger(int num) {
//        StringBuilder str = new StringBuilder();
//        str.append(num);
//        final String numStr = str.reverse().toString();
//        if (numStr.length() < 8) {
//            String blankStr = "";
//            for (int i=0;i<8 - numStr.length();i++) {
//                blankStr += "0";
//            }
//            return (numStr + blankStr);
//        } else {
//            return numStr.substring(0, 8);
//        }
//    }
    public static String getTraceID() {
        ConsoleContext consoleContext = ThreadLocalManager.getConsoleContext();
        if(consoleContext==null) {
            return null;
        }
        return consoleContext.getTraceId();
    }
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    public static String requestIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0];
    }

    /**
     * 保留小小数点后若干位
     */
    public static double scale(double number, int scale) {
        BigDecimal bigDecimal = new BigDecimal(number);
        return bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

}
